﻿var companyId = '';
var ztId = '';
var kjnd = '';
var kjkm = [];
//var aj = [];
//var pjh = [];
//var zph = [];
//var wldx = [];
//var xm = [];
//var bm = [];

var userdefault = {};
var params = {};
var dataList = [];
var mapList = [{id: "col_pzid", field: "pzid"}, {id: "col_pzrq", field: "pzrq"}, {id: "col_pzh", field: "pzh"},
    {id: "col_flxh", field: "flxh"}, {id: "col_zy", field: "zy"}, {id: "col_kjkm", field: "kjkm"},
    {id: "col_expeco", field: "expeco"}, {id: "col_expfunc", field: "expfunc"}, {id: "col_project", field: "project"},
    {id: "col_deppro", field: "deppro"}, {id: "col_department", field: "department"},
    {id: "col_j", field: "j"}, {id: "col_d", field: "d"},    {id: "col_yefxStr", field: "yefxStr"},{id: "col_ye",field: "ye"}];

//创建一个表格控件
var tbl = new QTable();

var bootstrap = function ($, learun) {

    var pageWidth = 1024;

    "use strict";
    var page = {
        init: function () {
            userdefault = learun.clientdata.get(['usersetting']);

            //初始化打印插件
            hiprint.init();
            pageWidth = ($('.lr-layout-grid').width());
            $("#divDataList").height($(window).height() - 200);

            tbl.BindDom("divDataList"); //绑定到模板
            tbl.setMaplist(mapList);  //设置数据映射关系
            page.bind();


        },
        bind: function () {
            $('#multiple_condition_query').lrMultipleQuery(function (queryJson) {
                page.search(queryJson);
            }, 440, 980);
            $('#pzrqMonth').lrselect({
                type: 'default',
                // 展开最大高度
                maxHeight: 300,
                placeholder: '月份',
                data: [
                    {'id': '01', 'text': '01'},
                    {'id': '02', 'text': '02'},
                    {'id': '03', 'text': '03'},
                    {'id': '04', 'text': '04'},
                    {'id': '05', 'text': '05'},
                    {'id': '06', 'text': '06'},
                    {'id': '07', 'text': '07'},
                    {'id': '08', 'text': '08'},
                    {'id': '09', 'text': '09'},
                    {'id': '10', 'text': '10'},
                    {'id': '11', 'text': '11'},
                    {'id': '12', 'text': '12'}
                ],
                select: function (item) {
                    if (!item || item.id == '-1') {
                        var beginDate = kjnd + "-01-01";
                        var day = new Date(kjnd, 12, 0);
                        var endDate = kjnd + "-" + 12 + "-" + day.getDate();
                        $("#pzrqStart").val('');
                        $("#pzrqEnd").val(endDate);
                    } else {
                        var kjqj = item.id;
                        var beginDate = kjnd + "-" + kjqj + "-01";
                        var day = new Date(kjnd, kjqj, 0);
                        var endDate = kjnd + "-" + kjqj + "-" + day.getDate();
                        $("#pzrqStart").val(beginDate);
                        $("#pzrqEnd").val(endDate);
                    }
                }
            });
            // 公司选择
            $('#company_select').lrselect({
                type: 'tree',
                // placeholder: '请选择机构',
                height: 300,
                maxHeight: 300,
                // 是否允许搜索
                //allowSearch: true,
                select: function (item) {
                    if (item && item.value != '-1') {
                        companyId = item.value;
                    }
                }
            });
            $('#company_select').lrselectRefresh({
                // 访问数据接口地址
                url: config.base_server() + 'companys/tree?access_token=' + config.getToken().access_token,
                // 访问数据接口参数
                param: {parentId: '0'}
            }).lrselectSet(userdefault.companyId);

            // 帐套选择
            $('#zt_select').lrDataItemSelect({
                code: 'ZT', maxHeight: 100,
                select: function (item) {
                    if (!item || item.id == '-1') {
                        ztId = '';
                    } else {
                        ztId = item.id;
                        $("#zt_title").html(item.text);
                    }
                }
            }).lrselectSetFirst();

            // 凭证类型
            $('#pzlxCode').lrDataItemSelect({
                code: 'PZLXS', maxHeight: 100,placeholder: "==请选择凭证类型==",
                select: function (item) {

                }
            });

            // 会计年度选择
            $('#kjnd_select').lrDataItemSelect({
                code: 'YEAR', maxHeight: 100, placeholder: "==请选择年份==",
                select: function (item) {
                    if (!item || item.value == '-1') {
                        kjnd = '';
                    } else {
                        kjnd = item.value;

                        var beginDate = kjnd + "-01-01";
                        var day = new Date(kjnd, 12, 0);
                        var endDate = kjnd + "-12-" + day.getDate();
                        //$("#pzrqStart").val(beginDate);
                        $("#pzrqEnd").val(endDate);

                        $('#kjkmCodes').lrlayerselect({
                            dataValueId: 'chrCode',
                            dataTextId: 'codeAndName',
                            reset: true,
                            url: config.base_server() + 'kjkms/list?companyId=' + companyId + '&ztId=' + ztId + '&kjnd=' + kjnd + '&status=1' + '&access_token=' + config.getToken().access_token,
                            grid: [
                                {label: '科目', name: 'codeAndName', width: 225, align: 'left'},
                                {
                                    label: "余额方向", name: "yefx", width: 50, align: "center",
                                    formatter: function (cellvalue) {
                                        return cellvalue == 1 ? "借" : "贷";
                                    }
                                },
                                {label: '是否明细', name: 'isLeaf', width: 1, align: 'left', hidden: true},
                                {label: '编号', name: 'chrCode', width: 120, align: 'left', hidden: true},
                                {label: '简称', name: 'chrName', width: 225, align: 'left', hidden: true}
                            ],
                            select: function (values, texts) {
                                kjkm = values;
                            }
                        });
                        //page.search({});
                    }
                }
            });

            // 查询
            $('#btn_Search').on('click', function () {
                page.search(params);
            });

            // 刷新
            $('#lr_refresh').on('click', function () {
                location.reload();
            });
            //预览
            $('#lr_printview').on('click', function () {
                var hiprintTemplate = null;
                var pzrqStart = $("#pzrqStart").val();
                var pzrqEnd = $("#pzrqEnd").val();
                learun.httpAsyncGet2(config.base_server() + 'printTempletes/findByCode', "&companyId=" + companyId + '&ztId=' + ztId + '&code=xsz', function (res) {
                    if (res.resp_code == 200) {
                        hiprintTemplate = new hiprint.PrintTemplate({
                            template: JSON.parse(res.data.templete),
                            paginationContainer: '.hiprint-printPagination'
                        });

                        var item = {};
                        item.pzflList = dataList;
                        if (item.pzflList.length > 38) {
                            item.pzflList = item.pzflList.slice(0, 72);
                        }
                        item.ztName = $("#zt_select .lr-select-placeholder").html();
                        item.pzrq = pzrqStart.substring(0, 10) + "至" + pzrqEnd.substring(0, 10);
                        // hiprintTemplate.print(item);
                        hiprintTemplate.resetPage();
                        $('#myModal .modal-body .prevViewDiv').html(hiprintTemplate.getHtml(item));
                        $('#myModal').modal('show');
                    }
                });
                $('#A4_printByHtml').click(function () {
                    hiprintTemplate.printByHtml($('#myModal .modal-body .prevViewDiv'));
                })
            });
            //打印
            $('#lr_print').on('click', function () {
                var hiprintTemplate = null;
                var pzrqStart = $("#pzrqStart").val();
                var pzrqEnd = $("#pzrqEnd").val();
                learun.httpAsyncGet2(config.base_server() + 'printTempletes/findByCode', "&companyId=" + companyId + '&ztId=' + ztId + '&code=xsz', function (res) {
                    if (res.resp_code == 200) {
                        hiprintTemplate = new hiprint.PrintTemplate({
                            template: JSON.parse(res.data.templete),
                            paginationContainer: '.hiprint-printPagination'
                        });

                        var item = {};
                        item.pzflList = dataList;

                        item.ztName = $("#zt_select .lr-select-placeholder").html();
                        item.pzrq = pzrqStart.substring(0, 10) + "至" + pzrqEnd.substring(0, 10);
                        hiprintTemplate.resetPage();
                        hiprintTemplate.print2(item);
                    }
                });
            });

            //导出Excel
            $("#lr_export_excel").on('click', function () {
                if (params.companyId == undefined) {
                    learun.alert.warning('请先查询要导出的数据！');
                    return;
                }
                params.access_token = config.getToken().access_token;

                learun.download({
                    url: config.base_server() + 'reports/xsz/excel',
                    param: params
                });
            });
            //导出pdf
            $("#lr_export_pdf").on('click', function () {
                if (params.companyId == undefined) {
                    learun.alert.warning('请先查询要导出的数据！');
                    return;
                }
                params.access_token = config.getToken().access_token;

                learun.download({
                    url: config.base_server() + 'reports/xsz/pdf',
                    param: params
                });
            });
        },

        search: function (param) {
            param = param || {};
            var pzrqStart = $("#pzrqStart").val();
            var pzrqEnd = $("#pzrqEnd").val();
            param.companyId = companyId;
            param.ztId = ztId;
            param.kjnd = kjnd;
            param.pzrqStart = pzrqStart;
            param.pzrqEnd = pzrqEnd;

            var formData = $('.lr-query-formcontent').lrGetFormData();

            param.kjkmEnable = formData.kjkmEnable;
            param.expecoEnable = formData.expecoEnable;
            param.expfuncEnable = formData.expfuncEnable;
            param.projectEnable = formData.projectEnable;
            param.depproEnable = formData.depproEnable;
            param.departmentEnable = formData.departmentEnable;

            var expecoEnable = formData.expecoEnable;
            var expfuncEnable = formData.expfuncEnable;
            var projectEnable = formData.projectEnable;
            var depproEnable = formData.depproEnable;
            var departmentEnable = formData.departmentEnable;

            if (formData.kjkmEnable == 0 && formData.expecoEnable == 0 && formData.expfuncEnable == 0 && formData.projectEnable == 0 && formData.depproEnable == 0 && formData.departmentEnable == 0) {
                learun.alert.error("至少选择一个辅助项");
                return;
            }

            param.kjkmXh = formData.kjkmXh;
            param.expecoXh = formData.expecoXh;
            param.expfuncXh = formData.expfuncXh;
            param.projectXh = formData.projectXh;
            param.depproXh = formData.depproXh;
            param.departmentXh = formData.departmentXh;

            if ($.isArray(kjkm)) {
                param.kjkmCodes = kjkm.join();
            }

            if (!!param.pzhStart) {
                param.pzhStart = completePzh(param.pzhStart, 4);
            }
            if (!!param.pzhEnd) {
                param.pzhEnd = completePzh(param.pzhEnd, 4);
            }

            params = param;

            learun.loading(true);
            learun.httpPost2(config.base_server() + 'reports/xsz_header2?access_token=' + config.getToken().access_token, param, function (res) {
                learun.loading(false);
                if (res.resp_code == 200) {
                    var col_html = "";
                    var th_html = "";
                    var tr_html = "";
                    var tr2_html = "";
                    var html = "";
                    var footer = "";
                    for (var i = 0; i < res.data.colData.length; i++) {
                        col_html += "<col width=\"" + res.data.colData[i].width + "\"/>";
                        th_html += "<th>" + res.data.colData[i].label + "</th>";
                        tr_html += " <td style=\"text-align:" + res.data.colData[i].align + "\" id=\"" + res.data.colData[i].name + "\"></td>";
                        if (res.data.colData[i].name == "col_j") {
                            tr2_html += " <td style=\"text-align: right\" id=\"total_j\">0.00</td>";
                        } else if (res.data.colData[i].name == "col_d") {
                            tr2_html += " <td style=\"text-align: right\" id=\"total_d\">0.00</td>";
                        } else {
                            tr2_html += " <td></td>";
                        }
                    }
                    html += "<table class=\"table\">";
                    html += col_html;
                    html += "<thead style=\"background-color: lavender;\">";
                    html += "<tr>";
                    html += th_html;
                    html += "</tr>";
                    html += "</thead><tbody><tr ondblclick=\"ViewData(this)\">";
                    html += tr_html;
                    html += "</tr></tbody>";
                    html += "</table>";

                    footer += "<footer>";
                    footer += "<table class=\"table\">";
                    footer += col_html;
                    footer += "<tbody><tr>";
                    footer += tr2_html;
                    footer += "</tr></tbody>";
                    footer += "</table>";
                    footer += "</footer>";

                    $("#divDataList").html(html);
                    $("#divDataList").after(footer);

                    tbl.BindDom("divDataList"); //绑定到模板
                    tbl.setMaplist(mapList);  //设置数据映射关系

                    learun.httpPost(config.base_server() + 'reports/xsz?access_token=' + config.getToken().access_token, param, function (res) {
                        learun.loading(false);
                        if (res.resp_code == 200) {
                            dataList = res.data;
                            var j = 0.0;
                            var d = 0.0;
                            for (var i = 0; i < dataList.length; i++) {
                                j += dataList[i].j;
                                d += dataList[i].d;
                                dataList[i].j = $.formatMoney(dataList[i].j, 2);
                                dataList[i].d = $.formatMoney(dataList[i].d, 2);
                                dataList[i].ye = $.formatMoney(dataList[i].ye, 2);
                            }
                            tbl.BindData(dataList);
                            $("#total_j").html($.formatMoney(j, 2));
                            $("#total_d").html($.formatMoney(d, 2));
                        } else {
                            learun.alert.error(res.resp_msg);
                            learun.httpErrorLog(res.resp_msg);
                        }
                    });

                } else {
                    learun.alert.error(res.resp_msg);
                    learun.httpErrorLog(res.resp_msg);
                }
            });


            $("#pzrq_title").html(pzrqStart.substring(0, 10) + "至" + pzrqEnd.substring(0, 10));
        }
    };
    page.init();
}

//查看凭证
function ViewData(row) {
    var data = row.data;
    var keyValue = data.pzid;
    var flxh = data.flxh;
    if (keyValue) {
        top.learun.frameTab.open({
            id: 'pz_view' + data.pzh,
            css: 'fa fa-file-text-o',
            name: '查看凭证' + data.pzh,
            path: config.webportal_server + 'pages/finance/pz/view.html?companyId=' + companyId + '&ztId=' + ztId + '&kjnd=' + kjnd + '&keyValue=' + keyValue + '&flxh=' + flxh + '&access_token=' + config.getToken().access_token
        });
    }
}

//不足4位补0
function completePzh(num, length) {
    return (Array(length).join('0') + num).slice(-length);
}
